// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import Shader from "../../Shader";


const { ccclass, property } = cc._decorator;

@ccclass
export default class BoxBlurShader extends Shader {
    @property(cc.Material)
    boxBlurMaterial: cc.Material = null;

    @property
    _blurRadius: number = 1;

    @property
    get blurRadius() {
        return this._blurRadius;
    }

    set blurRadius(value) {
        this._blurRadius = value;
        this.updateBlurRadius();
    }

    @property
    _iteration: number = 1;

    @property({
        min: 1
    })
    get iteration() {
        return this._iteration;
    }

    set iteration(value) {
        if (value == this._iteration) return;
        this._iteration = value;
        this.updateBlur();
    }

    @property
    _downLevel: number = 1;

    @property({
        min: 1
    })
    get downLevel() {
        return this._downLevel;
    }

    set downLevel(value) {
        if (value == this._downLevel) return;
        this._downLevel = value;
        this.updateBlur();
    }

    private _srcTex2D: cc.Texture2D = null;
    private _desTex2D: cc.Texture2D = null;
    private _originTexture: cc.Texture2D = null;

    protected start(): void {
        this.updateBlurRadius();
        this.updatePixelSize();

        this._originTexture = (this.renderComponent as cc.Sprite).spriteFrame.getTexture();

        this._srcTex2D = new cc.Texture2D();
        this._srcTex2D.setFlipY(true);
        this._desTex2D = new cc.Texture2D();
        this._desTex2D.setFlipY(true);

        this.updateBlur();
    }

    private updateBlurRadius() {
        this.boxBlurMaterial.setProperty("u_blurRadius", this._blurRadius);
    }

    private updatePixelSize() {
        this.boxBlurMaterial.setProperty("u_pixelSize", cc.v2(1 / this.node.width, 1 / this.node.height));
    }

    private updateBlur() {
        // (this.renderComponent as cc.Sprite).spriteFrame.setTexture(this._originTexture);
        // this.renderComponent['_updateMaterial']();
        // RenderUtils.renderNode(this.node, this._srcTex2D);
        // let temp;
        // for (let i = 0; i < this._iteration; i++) {
        //     RenderUtils.renderTexture(this._srcTex2D, this._desTex2D, this.boxBlurMaterial, this._downLevel);
        //     temp = this._desTex2D;
        //     this._desTex2D = this._srcTex2D;
        //     this._srcTex2D = temp;
        // }
        // (this.renderComponent as cc.Sprite).spriteFrame.setTexture(this._srcTex2D);
        // this.renderComponent['_updateMaterial']();
    }
}
